package com.tools.xxf.updatelib.apkinfo;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.Serializable;

/**
 * TODO:保存最新apk版本信息
 * @author XXF
 * Create Time : 2017/11/7 14:52
 */
public class ShareNewApk {
    private static String SHARE_APK_BEAN = "apkBean.file";
    private static String SHARE_APK_key = "apkBean.key";
    private final SharedPreferences mPreferences;

    public ShareNewApk(Context context) {
        mPreferences = context.getSharedPreferences(SHARE_APK_BEAN, Context.MODE_PRIVATE);
    }

    public ApkInFoBean getBean() {
        ApkInFoBean bean = null;
        String s = mPreferences.getString(SHARE_APK_key, "");
        Gson mGson = new Gson();
        try {
            bean = mGson.fromJson(s, ApkInFoBean.class);
        } catch (JsonSyntaxException exception) {
            exception.printStackTrace();
        }
        if (null != bean)
          LogUtils.d(mGson.toJson(bean));
        return bean;
    }

    public void saveBean(Serializable value) {
        SharedPreferences.Editor edit = mPreferences.edit();
        if (value == null) {
            edit.putString(SHARE_APK_key, null);
        } else {
            Gson gson = new Gson();
            String s = gson.toJson(value);
            edit.putString(SHARE_APK_key, s);
        }
        LogUtils.d("apkbean save successful");
        edit.apply();
    }
}
